<?php

declare(strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\Business\v2;

use App\Constants\Constants;

use App\Dao\BusinessDao;
use App\Dao\BusinessIndustryDao;
use App\Dao\LocationDao;
use App\Dao\UserBankDao;
use App\Dao\UserDao;
use App\Kernel\Util\UserJwtInstance;
use App\Model\UserBank;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;
use function AlibabaCloud\Client\json;

/**
 * 商家服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Business
 */

class BusinessService extends Service
{

    /**
     * @Inject
     * @var BusinessDao
     */
    public $dao;

    /**
     * @Inject
     * @var LocationDao
     */
    public $location_dao;

    /**
     * @Inject
     * @var UserDao
     */
    public $user_dao;

    /**
     * @Inject
     * @var UserBankDao
     */
    public $user_bank_dao;

    /**
     * 行业类别DAO
     *
     * @Inject
     * @var BusinessIndustryDao
     */
    public $business_industry_dao;

    /**
     * 获取商家加盟方式
     *
     * @return mixed
     */
    public function getJoiningWay()
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        $business = $user->business;

        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if ($business->status != 1) {
            $this->error('BUSINESS.NOT_PASS_CERT');
        }

        //判断商家的入驻方式，返回商家入驻方式 3：全店入驻，1：优惠券，2：现金抵用
        $type = 0;
        if ($business->enable_full_discount == 1) {
            $type = 3;
        }
        if ($business->enable_coupon == 1) {
            $type = 1;
        }
        if ($business->enable_voucher == 1) {
            $type = 2;
        }

        return $type;
    }

    /**
     * 商家认证资料
     * @param array $params
     * @return mixed
     */
    public function add(array $params)
    {

        $business = $this->dao->first([
            'user_id' => uid(),
        ]);


        if ($business && $business->status !== 3) {
            $this->error('BUSINESS.ALREADY_AUTH');
        }

        $province = $this->location_dao->getLocationByPid( [
            'pid' => $params['province_id']
        ] );

        $city = $this->location_dao->getLocationByPid( [
            'pid' => $params['city_id']
        ] );

        $district = $this->location_dao->getLocationByPid( [
            'pid' => $params['district_id']
        ] );


        // 下级地区不属于上级地区返回错误
        if ($province->pid !== $city->level || $city->pid !== $district->level) {
            $this->error('BUSINESS.LOCATION_ERROR');
        }

        //获取上级id，上级必须是渠道商
        $group = $this->user_dao::USER_CHANNEL_BUSINESS;
        $parent_id = $this->user_dao->getUserByIdentityCode($params['identity_code'],'id',$group);

        $bank = $this->user_bank_dao->insertGetId([
            'user_id' => uid(),
            'bank_name' => $params['bank_name'],
            'bank_account' => $params['bank_account'],
            'name' => $params['card_name'],
            'idcard' => $params['idcard'],
            'phone' => $params['card_phone'],
            'bank_branch' => $params['bank_branch'],
        ]);

        $data = [
            'user_id' => uid(),
            //-----店铺信息-----//
            'logo' => $params['logo'],
            'name' => $params['name'],
            'company_name' => $params['name'],//公司全称
            'industry_id' => $params['industry_id'],
            'province_id' => $province->pid,//省份id
            'province' => $province->name,//省份名称
            'city_id' => $city->pid,//城市id
            'city' => $city->name,//城市名称
            'district_id' => $district->pid,//县/区id
            'district' => $district->name,//县、区名称
            'address' => $params['address'],//详细地址
            'longitude' => $params['longitude'],//商家经度
            'latitude' => $params['latitude'],//商家纬度
            'location' => $params['location'],//定位时的位置
            //-----店铺信息-----//
            'phone' =>  $params['phone'],
            'tel' =>  $params['tel'],
            'forenoon_hours' => $params['forenoon_hours'],//上午营业时间
            'afternoon_hours' => $params['afternoon_hours'],//下午营业时间
            'status' => 2,//审核状态
            'description' => $params['description'],//店铺介绍
            'parent_id' => $parent_id['id'],//上级id
            //-----法人信息-----//
            'legal_name' => $params['business_name'],//公司法人
            'business_name' => $params['business_name'],//商家真实姓名
            'business_card_id' => $params['business_card_id'],//商家的身份证号码
            'business_bank_id' => $bank,//商家关联的银行卡id（非银行卡号）
            'business_idcard_positive' => $params['business_idcard_positive'],//商家身份证正面
            'business_idcard_negative' => $params['business_idcard_negative'],//商家身份证反面
            'company_license_pic' => $params['company_license_pic'],
            'business_cover' => $params['company_license_pic'],
            'other_certificates' => json_encode($params['other_certificates']),
            'science' => json_encode($params['science']),//详细地址
        ];

        $business_cert = $business ? $this->dao->update([
            ['user_id' => uid()]
        ], $data) : $this->dao->created($data);

        !$business_cert && $this->error();
    }

    /**
     * 选择入驻方式
     * @param array $params
     * @return mixed
     */
    public function setEntryMode(array $params)
    {
        $record = $this->redis->get(Constants::CODE_REDIS_PREFIX . $params['phone']);
        $record = !$record ?: json_decode($record, true);
        if (!$record || !isset($record['code']) || (string)$record['code'] !== $params['code']) {
            $this->error('COMMON.CODE_ERROR');
        }
        $this->redis->del(Constants::CODE_REDIS_PREFIX . $params['tel']);//删除验证码

        $result = $this->dao->update([
            ['user_id' => uid()]
        ], [
            'enable_full_discount' => $params['enable_full_discount'] ?? 0,
            // 没有启用全店打折时 全店打折比例设为0
            'full_discount_rate' => $params['enable_full_discount'] === 1 ? 0.15 : 0,
            'enable_coupon' => $params['enable_coupon'] ?? 0,
            'enable_voucher' => $params['enable_voucher'] ?? 0,
        ]);

        !$result && $this->error();
    }

    /**
     * 获取商家信息
     *
     * @return mixed
     */
    public function getInfo()
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        if( empty( $user ) ) {
            $this->error('BUSINESS.NOT_EXIST');
        }

        $business = $user->business;
        $business['type'] = '';

        !$business && $this->error('BUSINESS.NOT_EXIST');

        //返回商家入驻方式 1：全店打折 2：优惠券 3现金抵扣券
        if ( $business->enable_full_discount == 1 ) {
            $business['type'] = 3;
        } else if ( $business->enable_coupon == 1 ) {
            $business['type'] = 1;
        } else if ( $business->enable_voucher == 1 ) {
            $business['type'] = 2;
        } else {
            $business['type'] = '';
        }

        $parent = $this->user_dao->first($business->parent_id,false);

        $bank = $this->user_bank_dao->first($business->business_bank_id,false);


        $user['business']['identity_code'] = $parent['identity_code'];

        $user['business']['bank_name'] = $bank['bank_name'];
        $user['business']['bank_account'] = $bank['bank_account'];
        $user['business']['card_name'] = $bank['name'];
        $user['business']['idcard'] = $bank['idcard'];
        $user['business']['card_phone'] = $bank['phone'];
        $user['business']['bank_branch'] = $bank['bank_branch'];
        $user['business']['other_certificates'] = json_decode($business->other_certificates);

        $user['industry_name'] = $this->business_industry_dao->getBusinessIndustryById($business->industry_id);
        //返回用户所有信息
        return $user;
    }
}